package com.huirui.server.service;

import com.huirui.server.pojo.entity.OssFileInfo;
import com.huirui.server.util.AliOssUtil;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class FileService {


    @Resource
    private AliOssUtil aliOssUtil;

    @Resource
    private OssFileInfoService ossFileInfoService;

    @SneakyThrows
    public String uploadFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        long size = file.getSize();
        String contentType = file.getContentType();
        byte[] fileBytes = file.getBytes();
        String extension = FilenameUtils.getExtension(originalFilename);
        UUID uuid = UUID.randomUUID();
        String targetFileName = uuid + "." + extension;
        OssFileInfo ossFileInfo = new OssFileInfo();
        ossFileInfo.setFileSuffix(extension);
        ossFileInfo.setFileSize(size);
        ossFileInfo.setFileUuid(uuid.toString());
        ossFileInfo.setOriginalName(originalFilename);
        String fileUrl = aliOssUtil.upload(fileBytes, targetFileName);
        ossFileInfo.setContentType(contentType);
        ossFileInfo.setOssObjectName(targetFileName);
        ossFileInfo.setUploadTime(LocalDateTime.now());
        ossFileInfo.setFilePath(fileUrl);
        ossFileInfoService.save(ossFileInfo);
        return fileUrl;
    }
}
